﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Saber.Infrastructure.Http;
using Saber.Infrastructure.Logger;

namespace Saber.Plugin.Iciba
{
    public class Response
    {
        public int status { get; set; }
        public List<Translation> message { get; set; }
    }

    public class ErrorResponse
    {
        public int status { get; set; }
        public Error message { get; set; }
    }


    public class Error
    {
        public int error_code { get; set; }
        public string message { get; set; }
    }


    public class Translation
    {
        public string key { get; set; }
        public int value { get; set; }
        public string paraphrase { get; set; }
    }

    public class Main : IPlugin
    {
        private PluginInitContext _context;

        private static PluginMetadata metadata;

        static Main()
        {
            metadata = new PluginMetadata();
            metadata.ID = "095A6AE3A254432EBBD78F05A71D4982";
            metadata.Name = "金山词霸";
            metadata.Description = "金山词霸免费API";
            metadata.ActionKeyword = "icb";
            metadata.IcoPath = "Images\\iciba.png";

        }


        public List<Result> Query(Query query)
        {
            List<Result> results = new List<Result>();
            const string ico = "Images\\iciba.png";
            if (query.Search.Length == 0)
            {
                results.Add(new Result
                {
                    Title = "开始金山词霸在线中英互译",
                    SubTitle = "金山词霸在线免费API",
                    IcoPath = ico
                });
                return results;
            }


            //Dictionary<string, string> dic = new Dictionary<string, string>();
            //dic.Add("c", "word");
            //dic.Add("m", "getsuggest");
            //dic.Add("nums", "10");
            //dic.Add("is_need_mean", "0");
            //dic.Add("word", query.Search);
            var json = Http.Get(String.Format("https://dict-mobile.iciba.com/interface/index.php?c=word&m=getsuggest&nums=10&is_need_mean=0&word={0}", query.Search)).Result;

            Log.Debug(json);
            JObject jo = JObject.Parse(json);
            var status = jo.GetValue("status").Value<int>();

            if (status == 1)
            {
                Response o = JsonConvert.DeserializeObject<Response>(json);
                if (o.message != null)
                {
                    o.message.ForEach(o1 =>
                    {
                        results.Add(new Result
                        {
                            Title = o1.key,
                            SubTitle = o1.paraphrase,
                            Score = o1.value == 0 ? 1000 : o1.value,
                            IcoPath = ico,
                            Action = e=> { System.Diagnostics.Process.Start(string.Format("https://www.iciba.com/word?w={0}", o1.key)); return true; }
                        }); ;
                    });
                }
            }
            else
            {
                ErrorResponse o = JsonConvert.DeserializeObject<ErrorResponse>(json);
                string error = string.Format("{0} : {1}", o.message.error_code, o.message.message);

                results.Add(new Result
                {
                    Title = error,
                    IcoPath = ico
                });
            }


            return results;
        }

        public void Init(PluginInitContext context)
        {
            _context = context;
        }

        private System.Func<ActionContext, bool> copyToClipboardFunc(string text)
        {
            return c =>
            {
                if (this.copyToClipboard(text))
                {
                    _context.API.ShowMsg("翻译已被存入剪贴板");
                }
                else
                {
                    _context.API.ShowMsg("剪贴板打开失败，请稍后再试");
                }
                return false;
            };
        }

        private bool copyToClipboard(string text)
        {
            try
            {
                Clipboard.SetText(text);
            }
            catch (System.Exception e)
            {
                return false;
            }
            return true;
        }

        public PluginMetadata Metadata()
        {
            return metadata;
        }
    }
}
